package com.financing.platform.web.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.FpFundBuynoticeDTO;
import com.financing.platform.dto.FpFundCFDTO;
import com.financing.platform.dto.FpFundCompanyDTO;
import com.financing.platform.dto.FpFundInfoDTO;
import com.financing.platform.dto.FpFundMFDTO;
import com.financing.platform.dto.FpFundManagerDTO;
import com.financing.platform.dto.FpProjectTransferHisDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IFpFundCFService;
import com.financing.platform.service.IFpFundCompanyService;
import com.financing.platform.service.IFpFundInfoService;
import com.financing.platform.service.IFpFundMFService;
import com.financing.platform.service.IFpFundManagerService;
import com.financing.platform.service.IFpProjectTransferHisService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.RandomUtils;
import com.financing.platform.util.StringUtil;

/**
 * @Description: Controller
 * @author caojiayao
 * @version 1.0
 * @created 
 */
@Controller
@RequestMapping("/api/fund")
@Scope("prototype")
public class FpFundInfoAction  extends BaseAction {
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	@Autowired
	private IFpFundCFService fpFundCFService;
	
	@Autowired
	private IFpFundMFService fpFundMFService;
	
	@Autowired
	private IFpFundCompanyService fpFundCompanyService;
	
	@Autowired
	private IFpFundManagerService fpFundManagerService;
	
	@Autowired
	private IFpProjectTransferHisService fpProjectTransferHisService;
	
	@RequestMapping("/fpFundInfoQueryList.shtml")
	@ResponseBody
	public ResultMap queryList(HttpServletRequest request,
			HttpServletResponse response,FpFundInfoDTO dto,Pager pager) {
		try{
			log.info("Begin query fa user list!");
			
			dto.setBegin(pager.getStartIndex());
			dto.setPageSize(pager.getPageSize());
			
			int count = fpFundInfoService.countFpFundInfo(dto);
			pager.setTotalCount(count);
			List<FpFundInfoDTO> list = fpFundInfoService.listFpFundInfo(dto);
			//查找权限转移后的产品createBy
			if(list!= null && !list.isEmpty()){
				FpProjectTransferHisDTO tfdto = new FpProjectTransferHisDTO();
				for(FpFundInfoDTO projectVO : list){
					tfdto.setPProjectId(projectVO.getId());
					tfdto.setpProjectType("02");//“02：私募” 
					String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(tfdto);
					if(!StringUtil.isNullOrEmptyStr(createBy)){
						projectVO.setCreateBy(createBy);
					}
				}
			}
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			
			log.info("End querylist!");
		}catch(Exception e){
			log.error("queryList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			
			return resultMap;
	}
	
	@RequestMapping("/fpFundInfoAdd.shtml")
	@ResponseBody
	public ResultMap add(HttpServletRequest request,
			HttpServletResponse response,FpFundInfoDTO dto,FpFundBuynoticeDTO buyNoticeDto,String jjgsId,String jjjlIds) {
		try{
			log.info("Begin add info !");
			
			//参数缺失
			if(StringUtil.isNullOrEmptyStr(dto.getJjbm())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			//重复添加
			if(isRepeat(dto.getJjbm())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_REPEAT_LOSE);
				return resultMap;
			}
			
			
			DTOdateSet.setCreateInfo(dto, request.getSession());
			DTOdateSet.setUpdateInfo(dto, request.getSession());
			
			Integer id =fpFundInfoService.insertFpFundInfo(dto,buyNoticeDto);
			
			//add 基金信息关联基金公司
			if(jjgsId != null)
			this.addFpFundCF(jjgsId, dto.getJjbm(), dto.getJjmc());
			
			//add 基金信息关联基金经理
			if(jjjlIds != null)
			this.addFpFundMF(jjjlIds,dto);
			
			resultMap.getAttribute().put("id",id);
			
			if(id !=null && id >0 ){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End add fa user info !");
		}catch(Exception e){
			log.error("update fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
	}
	
	/**
	 * 判断重复
	 * @Title: isRepeat
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param jjbm
	 * @return Boolean 返回类型
	 * @throws
	 */
	private Boolean isRepeat(String jjbm){
		FpFundInfoDTO dto = new FpFundInfoDTO();
		dto.setJjbm(jjbm);
		if(fpFundInfoService.getFpFundInfo(dto) == null){
			return false;
		}
		return true;
	}
	
	/**
	 * 判断重复
	 * @Title: isRepeat
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param jjbm
	 * @return Boolean 返回类型
	 * @throws
	 */
	private Boolean isRepeatUpdate(String jjbm,Integer id){
		FpFundInfoDTO dto = new FpFundInfoDTO();
		dto.setJjbm(jjbm);
		dto = fpFundInfoService.getFpFundInfo(dto);
		if(dto != null && dto.getId().intValue() != id.intValue()){
			return true;
		}
		return false;
	}
	
	// 基金公司关联基金信息
	private void addFpFundCF(String jjgsId, String jjbm, String jjmc) {
		FpFundCompanyDTO dto = new FpFundCompanyDTO();
		dto.setId(new Integer(jjgsId));
		// get 基金信息
		FpFundCompanyDTO fundCompanyDTO = fpFundCompanyService.getFpFundCompany(dto);
		if (fundCompanyDTO != null && fundCompanyDTO.getJjgsbm() !=null) {
			// add 基金经理关联基金信息
			FpFundCFDTO fundCFDTO = new FpFundCFDTO();
			fundCFDTO.setJjbm(jjbm);
			fundCFDTO.setJjgsbm(fundCompanyDTO.getJjgsbm());
			fundCFDTO.setJjmc(jjmc);

			fpFundCFService.insertFpFundCF(fundCFDTO);
		}
	}
	
	// 基金经理关联基金
	private void addFpFundMF(String jjjlIds, FpFundInfoDTO dto) {
		String[] ids = jjjlIds.split(",");
		for (String id : ids) {
			if (!StringUtil.isNullOrEmptyStr(id)) {
				FpFundManagerDTO paramDto = new FpFundManagerDTO();
				paramDto.setId(new Integer(id));
				// get 基金经理信息
				FpFundManagerDTO fundManagerDTO = fpFundManagerService.getFpFundManager(paramDto);
				if (fundManagerDTO != null
						&& fundManagerDTO.getJjjlbm() != null) {
					// add 基金信息关联基金经理
					FpFundMFDTO fundMFDTO = new FpFundMFDTO();
					fundMFDTO.setJjbm(dto.getJjbm());
					fundMFDTO.setJjjlbm(fundManagerDTO.getJjjlbm());
					fundMFDTO.setJjmc(dto.getJjmc());
					fpFundMFService.insertFpFundMF(fundMFDTO);
				}
			}
		}

	}
	
	@RequestMapping("/fpFundInfoUpdate.shtml")
	@ResponseBody
	public ResultMap update(HttpServletRequest request,
			HttpServletResponse response,FpFundInfoDTO dto,FpFundBuynoticeDTO buyNoticeDto,String jjgsId,String jjjlIds) {
		try{
			log.info("Begin update fa user info !");
			//判断是否有权限修改产品
			if(!isAccess(dto.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			//参数缺失
			if(StringUtil.isNullOrEmptyStr(dto.getJjbm())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			//重复添加
			if(isRepeatUpdate(dto.getJjbm(),dto.getId())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_REPEAT_LOSE);
				return resultMap;
			}
			DTOdateSet.setUpdateInfo(dto, request.getSession());
			Map map =  getParameterMap(request);
			map.put("updateBy", dto.getUpdateBy());
			int count = fpFundInfoService.updateFpFundInfo(map);
			
			//update 基金信息关联基金公司
			if(jjgsId != null)
			this.updateFpFundCF(jjgsId, dto.getJjbm(), dto.getJjmc());
			
			//update 基金信息关联基金经理
			if(jjjlIds != null)
			this.updateFpFundMF(jjjlIds,dto);
			
			resultMap.getAttribute().put("update count",count);
			if(count >0){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End update fa user info !");
		}catch(Exception e){
			log.error("update fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
				
	}
	
	@RequestMapping("/fpFundInfoDelete.shtml")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request,
			HttpServletResponse response,FpFundInfoDTO dto) {
		try{
			log.info("Begin delete fa user info !");
			int count = fpFundInfoService.delFpFundInfo(dto.getId());
			
			resultMap.getAttribute().put("delete count",count);
			
			if(count > 0){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End delete fa user info !");
		}catch(Exception e){
			log.error("delete fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
				
	}
	
	
	@RequestMapping("/fpFundInfoDetail.shtml")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request,
			HttpServletResponse response, FpFundInfoDTO requestDto) {
		try{
			
			FpFundInfoDTO dto = fpFundInfoService.getFpFundInfo(requestDto);
			if(dto !=null){
				FpProjectTransferHisDTO tfdto = new FpProjectTransferHisDTO();
				tfdto.setPProjectId(dto.getId());
				tfdto.setpProjectType("02");//“02：私募” 
				String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(tfdto);
				if(!StringUtil.isNullOrEmptyStr(createBy)){
					dto.setCreateBy(createBy);
				}
			}
			//基金公司
			FpFundCompanyDTO companyDTO = new FpFundCompanyDTO();
			//基金经理人
			List<FpFundManagerDTO> managerList = new ArrayList<FpFundManagerDTO>();
			if(dto != null && !StringUtil.isNullOrEmptyStr(dto.getJjbm())){
				List<FpFundCompanyDTO> companyDTOs = fpFundCompanyService.getFpFundCompanyByFundId(dto.getJjbm());
				if(companyDTOs != null && !companyDTOs.isEmpty()){
					companyDTO = companyDTOs.get(0);
				}
				managerList = fpFundManagerService.listFpFundManagerByFundId(dto.getJjbm());
			}
			
			
			resultMap.setAttribute("detail", dto);
			resultMap.setAttribute("company", companyDTO);  
			resultMap.setAttribute("manager", getFpFundManagerDTO(managerList, dto.getJjjlbm()));
			resultMap.setAttribute("manager2", getFpFundManagerDTO(managerList, dto.getJjjlbm2()));
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query friendshipLink list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;

	}
	
	/**
	 * 获取私募基金编码
	 * @param request
	 * @param response
	 * @param requestDto
	 * @return
	 */
	@RequestMapping("/fpFundInfoCode.shtml")
	@ResponseBody
	public ResultMap fpFundInfoCode(HttpServletRequest request,
			HttpServletResponse response,String type,Integer digit) {
		try{
			
			if(digit == null || digit<= 0){
				digit = 6;
			}
			if(StringUtil.isNullOrEmptyStr(type)){
				type = "";
			}
			resultMap.setAttribute("code", type+RandomUtils.getRandomNumUtilsForString(digit));
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("	fpFundInfoCode error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;

	}
	private FpFundManagerDTO getFpFundManagerDTO(List<FpFundManagerDTO> managerList,String jjjlbm){
		if(managerList != null && !managerList.isEmpty()){
			for(FpFundManagerDTO dto : managerList){
				if(dto.getJjjlbm().equals(jjjlbm)){
					return dto;
				}
			}
		}
		return new FpFundManagerDTO();
	}
	
	// 基金公司关联基金信息
	private void updateFpFundCF(String jjgsId, String jjbm, String jjmc) {
		//删除
		FpFundCFDTO dto = new FpFundCFDTO();
		dto.setJjbm(jjbm);
		List<FpFundCFDTO> cfdtos =  fpFundCFService.listFpFundCF(dto);
		for(FpFundCFDTO ddto : cfdtos){
			fpFundCFService.delFpFundCF(ddto.getId());
		}
		
		//添加
		this.addFpFundCF(jjgsId, jjbm, jjmc);
		
	}
		
	// 基金经理关联基金
	private void updateFpFundMF(String jjjlIds, FpFundInfoDTO dto) {
		//删除
		FpFundMFDTO paramDto = new FpFundMFDTO();
		paramDto.setJjbm(dto.getJjbm());
		List<FpFundMFDTO> cfdtos =  fpFundMFService.listFpFundMF(paramDto);
		for(FpFundMFDTO ddto : cfdtos){
			fpFundMFService.delFpFundMF(ddto.getId());
		}
		
		//添加
		this.addFpFundMF(jjjlIds, dto);

	}
	
	/**
	 * 判断要修改的私募产品是否为当前用户所有
	 * @param projectId
	 * @param request
	 * @return
	 */
	private boolean isAccess(int projectId,HttpServletRequest request){
		
		UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
		
		//超级管理员具有所有产品的管理权限
		if(user.getUsername().equals("admin")){
			return true;
		}
		//权限扭转接收人
		FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
		dto.setPProjectId(projectId);
		dto.setpProjectType("02");//“02：私募”
		String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
		if(!StringUtil.isNullOrEmptyStr(createBy)){
			//是否是扭转接收人
			if(user.getUsername().equals(createBy)){
				return true;
			}else{
				return false;
			}
		}
		FpFundInfoDTO p = new  FpFundInfoDTO();
		p.setId(projectId);
		p = fpFundInfoService.getFpFundInfo(p);
		 if(p!=null && p.getCreateBy().equals(user.getUsername())){
			 return true;
		 }
		return false;
	}
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public  Map getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
	    Map returnMap = new HashMap();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = values[i] + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}
}
